(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.reportreq.listController', listController);
	listController.$inject = [ '$scope', '$q', '$filter', 'Constants', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig', 'authService', 'reportreqService', 'commonService' ];
	function listController($scope, $q, $filter, Constants, gridService, modalService, layoutConfig, validatorConfig, authService, reportreqService, commonService) {
		var ctrl = this, info = $scope.$stateParams.params, log = $scope.loggerFactory.getLogger("reportreqList");
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		
		ctrl.init = function() {
			ctrl.gridOptions = gridService.createGridOptions($scope, ctrl.layoutConfig.tableConfigs.table, paginationChanged, serviceRowSelectionChanged, sortChanged);
			ctrl.gridOptions.data = 'vm.searchCriteria.list';
			ctrl.searchCriteria = ctrl.gridOptions.defaultSearchCriteria;
			reportreqService.initListSearchOptions()//1. search option
			.then(function(result) {
				return $q(function(resolved, rejected) {
					ctrl.reportreqStatusOptions = result.reportreqStatusOptions || [];
					resolved();
				});
			})
			.then(function() {// 2. get list
				ctrl.search();
			});
		};

		ctrl.viewDocument = function(rowObj) {
			rowObj.srcTxnRef  = $filter('encode')(rowObj.requestId);
			rowObj.isTemporary = "N";
			commonService.openDocument(rowObj, 'do/cda/reportreq/download');
		};
		
		ctrl.downloadDocument = function(rowObj) {
			rowObj.srcTxnRef  = $filter('encode')(rowObj.requestId);
			rowObj.isTemporary = "N";
			commonService.download(rowObj, 'do/cda/reportreq/download');
		};
		
		ctrl.search = function() {
			ctrl.searchCriteria.list = [];
			authService.getList(ctrl.searchCriteria).then(
			function(response) {
				angular.merge(ctrl.searchCriteria, response.data);
				gridService.updateGridOptions(ctrl.searchCriteria, ctrl.gridOptions);
			},angular.noop);
		};

		function paginationChanged(pageNum, pageSize) {
			ctrl.searchCriteria.pageNum = pageNum;
			ctrl.searchCriteria.pageSize = pageSize;
			ctrl.searchCriteria.list = [];
			ctrl.search();
		}

		function serviceRowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedRows = selectedRows;
		}

		function sortChanged(sortColumns) {
			// now just support sort by one column
			ctrl.searchCriteria.sortDirection = sortColumns[0] ? sortColumns[0].direction : '';
			ctrl.searchCriteria.sortBy = sortColumns[0] ? sortColumns[0].sortBy : '';
			ctrl.search();
		}
	}
})(angular);